<template>
  <div class="user-edit">
    <Modal
      :title="title"
      v-model="visible"
      width="780"
      :styles="{ top: '20px', 'border-radius': '15px' }"
      :mask-closable="type == '0'"
      scrollable="true"
      transfer
    >
      <div>
        <Form ref="form" :model="form" :rules="ruleValidate" label-width="150">
          <FormItem label="规则名称：" prop="title">
            <Input v-model="form.title" />
          </FormItem>
          <FormItem label="消费积分获取规则：" prop="expenseMoney">
            <div style="display: flex; white-space: nowrap">
              <div style="margin-right: 10px">每消费</div>
              <Input v-model="form.expenseMoney" style="width: 100px" />元
              <div style="margin: 0 10px">获得</div>
              <FormItem prop="receiveIntegral">
                <Input
                  v-model="form.receiveIntegral"
                  style="width: 100px"
                />个人积分
              </FormItem>
            </div>
          </FormItem>
          <FormItem label="生效时间：" prop="validStartDate">
            <Row>
              <Col span="11">
                <DatePicker
                  v-model="form.validStartDate"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择生效时间"
                  style="width: 300px"
                ></DatePicker>
              </Col>
              <Col span="2" style="text-align: center">-</Col>
              <Col span="11">
                <FormItem prop="validEndDate">
                  <DatePicker
                    v-model="form.validEndDate"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择失效时间"
                    style="width: 300px"
                  ></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="积分规则类型">
            <RadioGroup v-model="form.type">
              <Radio :label="1" :value="1">通用规则</Radio>
              <Radio :label="2" :value="2">具体商品</Radio>
              <Radio :label="3" :value="3">会议室</Radio>
              <Radio :label="4" :value="4">场地</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="商户选择" v-if="form.type == 2">
            <Tree
              :data="MerchList"
              show-checkbox
              :load-data="loadData"
              ref="trees"
            ></Tree>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          size="large"
          :loading="submitLoading"
          @click="submit"
          >保存</Button
        >
        <Button size="large" @click="visible = false">取消</Button>
      </div>
      <!-- <div class="drawer-footer br" v-show="type != '0'">
        <Button type="primary" :loading="submitLoading" @click="submit"
          >提交</Button
        >
        <Button @click="visible = false">取消</Button>
      </div> -->
    </Modal>
  </div>
</template>

<script>
import {
  scIntegralGetedit,
  scIntegralGetAdd,
  scProductGetProductByCompanyId,
  scCompanyGetMerch,
} from "@/api/index";
export default {
  name: "integral-clean-addEdit",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
    },
  },
  data() {
    return {
      MerchList: [],
      selectMerch: [],
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      cleanDayShow: 0,
      form: {
        type: 1,
      },
      ruleValidate: {
        title: [{ required: true, message: "请输入名称", trigger: "blur" }],
        expenseMoney: [
          { required: true, message: "请输入消费金额", trigger: "blur" },
        ],
        receiveIntegral: [
          { required: true, message: "请输入积分", trigger: "blur" },
        ],
        validStartDate: [
          {
            required: true,
            type: "date",
            message: "请选择生效时间",
            trigger: "blur",
          },
        ],
        validEndDate: [
          {
            required: true,
            type: "date",
            message: "请选择失效时间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    visible(val) {
      if (!val) {
        this.$emit("on-submit", false);
      }
    },
  },
  methods: {
    loadData(item0, callback) {
      item0.loading = true;
      scProductGetProductByCompanyId({
        companyId: item0.id,
      }).then((res) => {
        console.log("懒加载");
        if (res.code == 200) {
          let data = res.result.map((item) => {
            item.title = item.storeName;
            item.type = 2;
            return item;
          });
          callback(data);
        }
      });
    },
    timeto(date) {
      var d = new Date(date);
      var hour = d.getHours() > 9 ? d.getHours() : "0" + d.getHours();
      var getMinutes =
        d.getMinutes() > 9 ? d.getMinutes() : "0" + d.getMinutes();
      var getSeconds =
        d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
      var datetime =
        d.getFullYear() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate() +
        " " +
        hour +
        ":" +
        getMinutes +
        ":" +
        getSeconds;

      return datetime;
    },
    submit() {
        let data = {};
      if (this.form.type == 2) {
        let list = this.$refs.trees.getCheckedNodes();
      
        let index = -1;
        if (list.length) {
          list.forEach((item) => {
            if (item.id) {
              index++;
              // if(item.)
              data["integralGetProducts[" + index + "].type"] = item.type;
              data["integralGetProducts[" + index + "].productId"] = item.id;
            }
          });
        }
      }
      this.form = {
        ...this.form,
        ...data,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form);
          if (this.form.id) {
            let data = {
              ...this.form,
            };
            delete data.integralGetProducts;
            scIntegralGetedit({
              ...data,
              validStartDate: this.timeto(this.form.validStartDate),
              validEndDate: this.timeto(this.form.validEndDate),
            }).then((res) => {
              if (res.success) {
                this.$Message.success("操作成功");
                this.$emit("on-submit", true);
                this.visible = false;
              }
            });
          } else {
            scIntegralGetAdd({
              ...this.form,
              validStartDate: this.timeto(this.form.validStartDate),
              validEndDate: this.timeto(this.form.validEndDate),
            }).then((res) => {
              if (res.success) {
                this.$Message.success("操作成功");
                this.$emit("on-submit", true);
                this.visible = false;
              }
            });
          }
        }
      });
    },
  },

  mounted() {
    scCompanyGetMerch().then((res) => {
      if (res.code == 200) {
        this.MerchList = [
          {
            title: "餐饮店铺",
            children: res.result.foodCompanys.map((item) => {
              return {
                ...item,
                title: item.companyName,
                loading: false,
                checked:
                  this.formData.integralGetProducts &&
                  this.formData.integralGetProducts.find((item0) => {
                    return item0.productId == item.id;
                  }),
                type: 1,
                children: [],
              };
            }),
          },
          {
            title: "培训店铺",
            children: res.result.trainCompanys.map((item) => {
              return {
                ...item,
                title: item.companyName,
                value: item.id,
                loading: false,
                checked:
                  this.formData.integralGetProducts &&
                  this.formData.integralGetProducts.find((item0) => {
                    return item0.productId == item.id;
                  }),
                type: 1,
                children: [],
              };
            }),
          },
        ];
      }
    });
    this.form = this.formData;
    console.log("formdata:", this.formData)
    if (this.form.id) {
      this.form = {
        ...this.formData,
        expenseMoney: String(this.formData.expenseMoney),
        receiveIntegral: String(this.formData.receiveIntegral),
      };

      this.title = "更新积分获取规则";
    } else {
      this.title = "添加积分获取规则";
      this.form.type = 1;
    }
  },
};
</script>

<style lang="less">
@import "@/styles/drawer-common.less";
.ivu-form-item-content {
  display: flex;
  .txt {
    width: 45px;
    &.ml {
      margin-left: 10px;
    }
  }
}
</style>

